<template>
  <el-tree
      :data="data"
      show-checkbox
      node-key="id"
      default-expand-all
      :expand-on-click-node="false" >
      <el-col :span="24"  class="custom-tree-node" slot-scope="{ node, data }">
        <span  v-if="!validEdit(data.id)">
                <el-col :span="2">{{ node.label }}</el-col>
        </span>
        <span v-if="!validInsert(data.id) && !validEdit(data.id)" >
          <el-button
              type="text"
              size="mini"
              @click="doAppend(data.id)">
            添加
          </el-button>
                    <el-button
                        type="text"
                        size="mini"
                        @click="doEdit(data.id)">
              编辑
          </el-button>
          <el-button
              type="text"
              size="mini"
              @click="remove(node, data)">
            删除
          </el-button>
        </span>
        <span  v-if="validInsert(data.id)||validEdit(data.id)">
          <el-col :span="6">
                      <el-input placeholder="请输入权限标识符" size="small" v-model="userRole[data.id]"></el-input>
          </el-col>
          <el-col :span="6">
                      <el-input placeholder="请输入权限名称"  size="small" v-model="roleName[data.id]"></el-input>
          </el-col>
          <el-col :span="6" offset="1">
                      <el-button type="primary" size="small" @click="resolve(data)">保存</el-button>
            <el-button type="primary" size="small" @click="cancel(data.id)">取消</el-button>
          </el-col>
        </span>
      </el-col>
  </el-tree>
</template>

<script>
import CloneUtil from "@/core/utils/CloneUtil";
import {RoleApi} from "@/core/request/api/RoleApi";

class AntVData {
  id;
  isLeaf;
  label;
  name;
  size;
}

export default {
  name: "roleTable",
  data() {
    return {
      data: null,
      isInsert: {},
      isEdit: {},
      userRole: {},
      roleName: {}
    }
  },
  computed:{

  },
  methods: {
    validInsert(id) {
      return this.isInsert[id]
    },
    validEdit(id) {
      return this.isEdit[id]
    },
    doAppend(id) {
      console.log(id);
      this.isInsert[id] = true
    },
    doEdit(id) {
      console.log(id);
      this.isEdit[id] = true
    },
    remove(node, data) {
      this.$confirm('确定删除角色【' + data.label + '】吗？其所有子类角色将移动到当前角色的父类角色中', '提示',{
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消修改'
      }).then(()=>{
        RoleApi.delete(data.id).then(res =>{
          if (!res.data.code){
            this.$message.success("删除成功")
            this.$router.push("refresh")
          }
        })
      }).catch(()=>{})
    },
    addNode(id) {
      console.log("新增节点，编号：" + id)
      Object.assign(this.isInsert, {[id]: false})
      Object.assign(this.isEdit, {[id]: false})
      Object.assign(this.userRole, {[id]: null})
      Object.assign(this.roleName, {[id]: null})
    },
    validUserRole(userRole){
      var oriNodes = this.$store.state.role.nodes;
      var valid = oriNodes.filter(v => v.name == userRole);
      if (valid?.constructor == Object?valid!=null:valid.length>0){
        return false
      }
      return true
    },
    resolve(data) {
      data.isLeaf = false
      var antVData = new AntVData();
      var number = Object.getOwnPropertyNames(this.isInsert).length - 1;
      antVData.children = []
      antVData.id = (number).toString()+1;
      antVData.label = this.roleName[data.id];
      var oriNodes = this.$store.state.role.nodes;
      // if (this.validUserRole(this.userRole[data.id])){
      //   this.$message.warning("当前标识已存在！")
      //   return
      // }
     if (this.isInsert[data.id]){
       RoleApi.addRole({fid:data.id,userRole:this.userRole[data.id],roleName:this.roleName[data.id]})
           .then(res=>{
             if (!res.data.code){
               this.addNode(number)
               antVData.name = this.userRole[data.id]
               antVData.isLeaf = true
               antVData.size = (data.size - 15) ? data.size - 15 : 15
               data.children.push(antVData)
               oriNodes.push(antVData)
               var filter = oriNodes.filter(v => v.id == data.id);
               console.log(filter)
               filter.children == null ?
               filter.children = [] : filter.children;
               filter.children.push(antVData)
               filter.isLeaf = false
               let json = []
               var edges = this.$store.state.role.edges;
               edges.forEach(v => {
                 json.push({source: v.source, target: v.target})
               })
               json.push({source: data.id, target: antVData.id})
               this.$store.state.role.edges = json
               this.main()
               this.$message.success("新增成功！")
               return
             }
           })
     }
     else if (this.isEdit[data.id]){
        RoleApi.updateRole({id:data.id,userRole:this.userRole[data.id],roleName:this.roleName[data.id]}).then(res=>{
          if (!res.data.code){
            this.$router.push("/refresh")
            this.$message.success("修改成功！")
            return
          }
          this.$message.error(res.data.msg)
        })
     }
    },
    cancel(id) {
      this.isInsert[id] = this.isEdit[id] = false
    },
    init(data, _, __, i) {
      console.log(data)
      if (data?.constructor == Object) {
        if (null == data.children || data.children.length == 0) {
          Object.assign(_, {[data.id]: false})
          Object.assign(__, {[data.id]: null})
          return i
        }
      } else {
        if (null == data || data.length == 0) return i
      }
      for (let j = 0; j < data.length; ++j,++i) {
        console.log(`正在处理第${i}个数据,id=${data[j].id}...`)
          Object.assign(_, {[data[j].id]: false})
          Object.assign(__, {[data[j].id]: null})
          this.init(data[j].children, _, __, i+1);
          console.log(_)
      }
    },
    main(){
      let f = true
      while (f) {
        this.data = this.$store.state.role.nodes.slice(0, 1)
        if (this.data && this.data[0]) {
          f = false
          let _ = {}
          let __={}
          console.log("进行data初始化...")
          this.init(this.data,_,__,0)
          this.isInsert=_
          this.isEdit=CloneUtil.clone(_)
          this.roleName=__
          this.userRole=CloneUtil.clone(__)
        }
      }
    }
  },
  mounted() {
    this.main()
  }
}
</script>

<style scoped>
</style>